﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using UCCLIGHT2.Encoder.Util;
using System.Xml.Linq;
using System.Net;
using System.IO;

namespace UCCLIGHT2.Encoder.ConsoleApp
{
    class Program
    {
        static EncoderUtil encoder_util;
        static bool isRun = false;
        static Thread th_main;

        static void Main(string[] args)
        {
            InitProperties();
            StartEncoder();
        }

        private static void InitProperties()
        {
            encoder_util = new EncoderUtil("Files");
        }

        private static void StartEncoder()
        {
            WriteConsoleLog("Encoder Start");

            isRun = true;

            th_main = new Thread(new ThreadStart(EncodeWorker));
            th_main.Start();
        }

        static Thread encode_th;
        private static void EncodeWorker()
        {
            while (isRun)
            {
                if (encoder_util.IsEncoding)
                {
                    WriteConsoleLog("Encoding..." + encoder_util.Progress.ToString());
                }
                else
                {
                    WriteConsoleLog("Encoder Waiting...");
                    encode_th = new Thread(new ThreadStart(DoEncode));
                    encode_th.Start();
                }                
                //Waiting...
                Thread.Sleep(1000);
            }
        }

        static void DoEncode()
        {
            HttpWebRequest req;
            Uri target = new Uri("http://localhost:17627/Default.aspx");
            req = (HttpWebRequest)HttpWebRequest.Create(target);

            if (req.GetResponse().ContentLength > 0)
            {
                //Read XML
                StreamReader sr = new StreamReader(req.GetResponse().GetResponseStream());
                string data = sr.ReadToEnd();
                
                //Parse XML
                XElement unencoded_item = XElement.Parse(data, LoadOptions.None);
                if (unencoded_item.Elements().Count() != 0)
                {
                    int idx = int.Parse(unencoded_item.Element("UCCIDX").Value);
                    string filename = unencoded_item.Element("UCCFile").Value;
                    int e_option = int.Parse(unencoded_item.Element("UCCEncodingOption").Value);

                    //Do Encoding
                    WriteConsoleLog("Encoder Start!!");
                    encoder_util.DoEncode(idx, filename, e_option);
                }
                encode_th.Abort();

                if (sr != null)
                {
                    sr.Close();
                }
            }
        }

        private static void WriteConsoleLog(string msg)
        {
            Console.WriteLine(DateTime.Now.ToString("MM-dd HH:mm:ss") + " - " + msg);
        }
    }
}
